package mspbots.data.sync.contactscience.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.contactscience.model.ContactScienceCallblock;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ContactScienceCallblockReceiver extends BaseReceiver {

    @RabbitListener(queues = "contactscience.callblock.sync")
    public void processCallblock(ResultMessageModel model) {
        log.debug("processCallblock[contactscience.callblock.sync] ResultMessageModel {}", model);
        if (!ObjectUtils.isEmpty(model.getEntity()) && ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            JsonNode node = model.getEntity();
            ContactScienceCallblock data = ContactScienceCallblock.builder()
                    .userName(node.get("userName").asText())
                    .summaryDay(LocalDate.parse(node.get("summaryDay").asText(),DateTimeFormatter.ISO_LOCAL_DATE))
                    .build();
            data.setExtend(node);
            data.setTenantId(model.getTenantId());
            data.setSyncTime(LocalDateTime.now());

            Optional<Long> id = this.databaseClient.execute("select id from contactscience_callblock " +
                    "where tenant_id =:tenantId and user_name =:userName and summary_day =:summaryDay")
                    .as(Long.class)
                    .bind("tenantId", data.getTenantId())
                    .bind("userName", data.getUserName())
                    .bind("summaryDay", data.getSummaryDay())
                    .fetch().one().blockOptional(Duration.ofSeconds(10));

            if (id.isPresent() && id.get() > 0) {
                data.setId(id.get());
                this.databaseClient.update().table(ContactScienceCallblock.class).using(data).fetch().rowsUpdated().block();
            } else {
                this.databaseClient.insert().into(ContactScienceCallblock.class).using(data).fetch().rowsUpdated().block();
            }
        }
    }
}
